package com.javachmapi.weixinlogin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.javachmapi.weixinlogin.auth.AccessToken;
import com.javachmapi.weixinlogin.config.APIConfig;
import com.javachmapi.weixinlogin.config.WechatConfig;
import com.javachmapi.weixinlogin.entity.User;
import com.javachmapi.weixinlogin.dao.UserDao;
import com.javachmapi.weixinlogin.entity.WechatUserInfo;
import com.javachmapi.weixinlogin.service.UserService;
import com.javachmapi.weixinlogin.utils.AesUtil;
import com.javachmapi.weixinlogin.utils.DateUtils;
import com.javachmapi.weixinlogin.utils.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * (User)表服务实现类
 *
 * @author 宋利军
 * @since 2020-05-27 04:01:15
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private WechatConfig wechatConfig;
    @Autowired
    private UserDao userDao;

    /**
     * 1、网页授权回调地址处理
     * @return
     */
    @Override
    public Map<String, String> wechatLoginUrl() {
        Map<String,String> map = new HashMap<String,String>();
        //加密相关
        String content = APIConfig.PWD_MD5+ DateUtils.getYYYYMMdd();
        byte[] encrypt = AesUtil.encrypt(content, AesUtil.PASSWORD_SECRET_KEY, 16);
        String parseByte2HexStr = AesUtil.parseByte2HexStr(encrypt);

        StringBuilder url = new StringBuilder();
        url.append(APIConfig.AUTHORIZATION_URL);
        url.append("?appid=" + wechatConfig.getOpenAppId());
        //微信回调返回的code
        url.append("&redirect_uri=" + wechatConfig.getNotifyUrl());
        url.append("&response_type=code");
        url.append("&scope=" + APIConfig.QRCONNECT_SCOPE_SNSAPI_LOGIN);
        url.append("&state="+parseByte2HexStr);
        map.put("url", url.toString());
        return map;
    }

    /**
     * 2、获取AccessToken
     * @param code
     * @return
     */
    @Override
    public AccessToken getAccessToken(String code) {
        StringBuilder accessTokenUrl = new StringBuilder();
        accessTokenUrl.append(APIConfig.ACCESS_TOKEN_URL);
        accessTokenUrl.append("?appid="+wechatConfig.getOpenAppId());
        accessTokenUrl.append("&secret="+wechatConfig.getOpenAppSecret());
        accessTokenUrl.append("&code="+code);
        accessTokenUrl.append("&grant_type=authorization_code");
        log.info("\nappid:{}\n,secret:{}\n,code:{}\n,grant_type:{}\n",
                wechatConfig.getOpenAppId(),
                wechatConfig.getOpenAppSecret(),
                code,
                "authorization_code");
        System.out.println(accessTokenUrl);
        String responseContent = HttpClientUtils.getInstance().sendHttpGet(accessTokenUrl.toString());
        log.info("responseContent"+responseContent);
        if (responseContent == null || responseContent == "") {
            return null;
        }
        JSONObject parseObject = JSONObject.parseObject(responseContent);
        AccessToken accessToken = JSONObject.toJavaObject(parseObject, AccessToken.class);

        return accessToken;
    }

    /**
     * 获取用户统一标识。针对一个微信开放平台帐号下的应用，
     * 同一用户的unionid在多个应用中是唯一的。
     * 此方法不牵扯到多个应用时候可以不用。
     *
     * 此处用到只是为了获取微信扫码用户的省份城市(此信息获取的只是微信用户所填的城市省份，
     * 并不是用户的实时位置信息，如果用户未填写是获取不到的。)
     */
    @Override
    public WechatUserInfo getWechatUserInfo(String access_token,String openid) {
        StringBuilder unionIDUrl = new StringBuilder();
        unionIDUrl.append(APIConfig.GET_UNIONID_URL);
        unionIDUrl.append("?access_token="+access_token);
        unionIDUrl.append("&openid="+openid);
        String responseContent = HttpClientUtils.getInstance().sendHttpGet(unionIDUrl.toString());
        if (responseContent == null || responseContent == "") {
            return null;
        }
        JSONObject parseObject = JSONObject.parseObject(responseContent);
        WechatUserInfo wechatUserInfo = JSONObject.toJavaObject(parseObject, WechatUserInfo.class);
        return wechatUserInfo;
    }

    /**
     * 判断openId是否存在
     * @param openId
     * @return
     */
    @Override
    public User findUserByOpenid(String openId) {
        User user = userDao.findUserByOpenid(openId);
        return user;
    }

    @Override
    public void save(User user) {
        userDao.insert(user);
    }
}